<template>
    <canvas ref="canvas" class="rain-canvas"></canvas>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const canvas = ref(null)
let animationFrameId = null
let raindrops = []

const RAIN_COUNT = 300 // 雨滴数量

onMounted(() => {
    const ctx = canvas.value.getContext('2d')
    resizeCanvas()

    // 创建雨滴数组
    for (let i = 0; i < RAIN_COUNT; i++) {
        raindrops.push({
            x: Math.random() * canvas.value.width,
            y: Math.random() * -canvas.value.height,
            length: Math.random() * 10 + 5, // 雨滴长度 5~15px
            speed: Math.random() * 3 + 2, // 下落速度 2~5px/帧
            xVariation: (Math.random() - 0.5) * 2, // 水平漂移 -1~1
        })
    }

    function resizeCanvas() {
        canvas.value.width = window.innerWidth
        canvas.value.height = window.innerHeight
    }

    function draw() {
        const ctx = canvas.value.getContext('2d')

        // 透明背景，实现尾迹效果
        ctx.fillStyle = 'rgba(255, 255, 255, 0.05)'
        ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)

        for (let drop of raindrops) {
            ctx.beginPath()
            ctx.moveTo(drop.x, drop.y)
            ctx.lineTo(drop.x + drop.xVariation, drop.y + drop.length)
            ctx.strokeStyle = `rgba(0, 0, 255, ${Math.random() * 0.5 + 0.2})`
            ctx.lineWidth = Math.random() * 1 + 0.5
            ctx.stroke()
        }

        update()
        animationFrameId = requestAnimationFrame(draw)
    }

    function update() {
        for (let drop of raindrops) {
            drop.x += drop.xVariation
            drop.y += drop.speed

            if (drop.y > canvas.value.height) {
                drop.y = Math.random() * -canvas.value.height
                drop.x = Math.random() * canvas.value.width
            }
        }
    }

    // 启动动画
    draw()

    // 监听窗口大小变化
    window.addEventListener('resize', resizeCanvas)
})

onUnmounted(() => {
    cancelAnimationFrame(animationFrameId)
    window.removeEventListener('resize', resizeCanvas)
})
</script>

<style scoped>
.rain-canvas {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: transparent; /* 黑色背景模拟夜晚 */
}
</style>
